import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

public class CodeFoldingPanel extends JPanel {
    private final JTextComponent textComponent;
    private final List<FoldRegion> foldRegions = new ArrayList<>();
    
    // 用于延迟更新折叠区域的定时器
    private Timer updateTimer;
    
    public CodeFoldingPanel(JTextComponent textComponent) {
        this.textComponent = textComponent;
        setPreferredSize(new Dimension(20, 0));
        setOpaque(true);
        setBackground(Color.LIGHT_GRAY);
        
        // 添加鼠标监听器处理折叠操作
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int y = e.getY();
                for (FoldRegion region : foldRegions) {
                    if (Math.abs(y - region.yPosition) < 10) { // 10像素的点击容差
                        toggleFold(region);
                        break;
                    }
                }
            }
        });
        
        // 监听文本变化
        textComponent.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                scheduleUpdate();
            }
            
            @Override
            public void removeUpdate(DocumentEvent e) {
                scheduleUpdate();
            }
            
            @Override
            public void changedUpdate(DocumentEvent e) {
                scheduleUpdate();
            }
        });
    }
    
    // 延迟更新折叠区域，避免频繁计算
    private void scheduleUpdate() {
        if (updateTimer != null && updateTimer.isRunning()) {
            updateTimer.restart();
        } else {
            updateTimer = new Timer(500, e -> {
                updateFoldRegions();
                updateTimer = null;
            });
            updateTimer.setRepeats(false);
            updateTimer.start();
        }
    }
    
    private void updateFoldRegions() {
        foldRegions.clear();
        
        try {
            String text = textComponent.getText();
            // 查找可以折叠的区域（如大括号包围的代码块）
            int start = 0;
            int braceCount = 0;
            while ((start = text.indexOf('{', start)) != -1) {
                // 限制扫描的范围，避免处理过大的文件时卡顿
                if (braceCount++ > 100) break;
                
                int end = findMatchingBrace(text, start);
                if (end != -1) {
                    FoldRegion region = new FoldRegion(start, end);
                    foldRegions.add(region);
                }
                start++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        repaint();
    }
    
    private int findMatchingBrace(String text, int openingBrace) {
        int count = 1;
        for (int i = openingBrace + 1; i < text.length() && i < openingBrace + 10000; i++) {
            char c = text.charAt(i);
            if (c == '{') {
                count++;
            } else if (c == '}') {
                count--;
                if (count == 0) {
                    return i;
                }
            }
        }
        return -1;
    }
    
    private void toggleFold(FoldRegion region) {
        region.collapsed = !region.collapsed;
        
        try {
            if (region.collapsed) {
                // 折叠代码
                int start = region.startOffset + 1;
                int end = region.endOffset;
                String placeholder = " ... ";
                
                // 注意：这里简化处理，实际应用中需要更复杂的逻辑来处理折叠
                // 例如记录原始文本，支持展开等
            } else {
                // 展开代码
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        repaint();
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        // 绘制折叠标记
        g.setColor(Color.DARK_GRAY);
        
        try {
            for (FoldRegion region : foldRegions) {
                // 计算折叠标记的位置
                Rectangle startRect = textComponent.modelToView(region.startOffset);
                region.yPosition = startRect.y + startRect.height / 2;
                
                // 绘制折叠图标
                int x = 10;
                int y = region.yPosition;
                
                // 绘制圆形标记
                g.drawOval(x - 6, y - 6, 12, 12);
                
                // 绘制 +/- 符号
                g.drawLine(x - 4, y, x + 4, y); // 水平线
                if (!region.collapsed) {
                    g.drawLine(x, y - 4, x, y + 4); // 垂直线（形成+号）
                }
            }
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
    
    // 折叠区域类
    private static class FoldRegion {
        int startOffset;
        int endOffset;
        int yPosition;
        boolean collapsed = false;
        
        FoldRegion(int start, int end) {
            this.startOffset = start;
            this.endOffset = end;
        }
    }
}